<!DOCTYPE html>
<html>
  <head>
    <title>OpenAI Chat</title>
  </head>
  <body>
    <div id="chat-container">
      <div id="chat-messages"></div>
      <input type="text" id="chat-input" />
      <button id="chat-submit">Submit</button>
    </div>
    <script>
      // 填写 API Key
      //   const apiKey = "YOUR_API_KEY";
      const apiKey = "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";

      // API 地址
      const apiUrl = "https://api.openai.com/v1/engines/davinci/completions";

      // 获取元素
      const chatInput = document.getElementById("chat-input");
      const chatSubmit = document.getElementById("chat-submit");
      const chatMessages = document.getElementById("chat-messages");

      // 提交按钮点击事件处理程序
      chatSubmit.addEventListener("click", () => {
        // 获取用户输入
        const input = chatInput.value;

        // 请求数据
        const data = {
          prompt: input,
          temperature: 0,
          max_tokens: 300,
          n: 1,
          stop: "\n",
        };

        // 请求头
        const headers = {
          "Content-Type": "application/json",
          Authorization: `Bearer ${apiKey}`,
        };

        // 发送请求
        fetch(apiUrl, {
          method: "POST",
          headers: headers,
          body: JSON.stringify(data),
        })
          .then((response) => response.json())
          .then((response) => {
            // 输出响应
            const message = `User: ${input}\nBot:
                ${response.choices[0].text};`;
            chatMessages.innerHTML += `<p>${message}</p>`;
            chatInput.value = "";
          })
          .catch((error) => {
            console.error(error);
          });
      });
    </script>
  </body>
</html>
